package com.canbot.u05.activity;


import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.MainApplication;
import com.canbot.u05.R;
import com.canbot.u05.activity.version.MobVersionResponse;
import com.canbot.u05.activity.version.NewVersionActivity;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.PadSocketManager;
import com.canbot.u05.socket.SocketManager;
import com.canbot.u05.utils.ActivityUtil;
import com.canbot.u05.utils.Config;
import com.canbot.u05.utils.ConstUtils;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.utils.WifiUtils;
import com.canbot.u05.utils.XunFeiYuYingUtils;
import com.canbot.u05.view.CenterCommonHintDialog;
import com.canbot.u05.view.CenterDialog2;
import com.canbot.u05.view.CenterErrorDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页
 */

public class MyRobotActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private static final String TAG = "MyRobotActivity";
        private static final int CONNECTING = 0;

        private static final int CONNECTION_FAILURE_FIRST = 0;

        private static final int CONNECTION_FAILURE_SECOND = 1;

        private static final int CONNECTING_SUCCESS = 1;

        private static final int CONNECTING_FIRST = 2;

        private static final int FIRST_HINT = 3;

        private static final int SECOND_HINT = 4;

        private static final int CONN_HINT = 6;

        private static final int DISCONN_HINT = 5;

        private static final int DISCONNECT = 7;

        private CenterDialog2 centerDialog;

        private CenterDialog2 mSuccessDialog;

        private CenterDialog2 mConnectingDialog;

        private CenterCommonHintDialog mConfirmConnectionDialog;

        private boolean idfirst = false;

        private CenterErrorDialog mFailureDialog;

        private Button btDisconnect;

        private Button btConn;

        private TextView textName;

        private static final int CONNECTION_TIME = 60 * 1000;

        private  boolean disconnectNetSuccess = false;
        private  long disconnectTime;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_my_robot);
                findViewById(R.id.icon_control).setOnClickListener(this);
                findViewById(R.id.icon_editor).setOnClickListener(this);
                btDisconnect = (Button) findViewById(R.id.btn_disconnect_net);
                btConn = (Button) findViewById(R.id.btn_conn_net);
                textName= (TextView) findViewById(R.id.text_name);

                String a = getResources().getString(R.string.my_uu_name);
                String b = String.format(a, Config.ROBOT_NAME);
                textName.setText(b);


                XunFeiYuYingUtils.getInstance().init(getApplicationContext());
                this.registerReceiver(mSendResultReceiver, new IntentFilter(MainApplication.ACTION_CONNECT_SUCCESS));

                String currentSSID = getCurrentSSID();
                if (WifiUtils.isU05Wifi(currentSSID)) {
                        if (!MainApplication.isConnect) {
                                MainApplication.getInstance().getServerIp();
                        }
                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_PAD_CONN_HOTSPOT, currentSSID);
                        initConnect();
                }
                else {
                        ToastTools.newInstance(this).showText(getString(R.string.not_connected_chest_hotspot));
                }

        }

        /**
         * 检测版本
         */
        private void checkVersion(){
                String downloadUrl = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/allversionservlet" ;
                OkHttpUtils.request(downloadUrl, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Logger.e(TAG,"onSuccess==="+result);
                                if (!TextUtils.isEmpty(result)){
                                        List<MobVersionResponse> needUpdateLists =  new ArrayList<>();
                                        List<MobVersionResponse> mobVersionResponses = JSON.parseArray(result, MobVersionResponse.class);
                                        if (mobVersionResponses != null && mobVersionResponses.size() > 0) {
                                                Logger.e(TAG,"e====="+mobVersionResponses.size());
                                                for (MobVersionResponse m:mobVersionResponses) {
                                                        String packageName = m.getPackageName();
                                                        int appVersionCode = ActivityUtil.getAppVersionCode(MainApplication.getInstance().getApplicationContext(),packageName);
                                                        int version = Integer.parseInt(m.getVersion());
                                                        Logger.d(TAG,"tempVersionCode="+version);
                                                        Logger.d(TAG,"appVersionCode="+appVersionCode);
                                                        if (version > appVersionCode){
                                                                needUpdateLists.add(m);
                                                        }
                                                }
                                        }
                                        if (needUpdateLists.size()>0){
                                                Intent intent = new Intent(MyRobotActivity.this, NewVersionActivity.class);
                                                intent.putExtra("versionInfo",JSON.toJSONString(needUpdateLists));
                                                startActivity(intent);
                                        }
//                                        else {
//                                                runOnUiThread(new Runnable() {
//                                                        @Override
//                                                        public void run() {
//                                                                ToastUtil.show(MyRobotActivity.this.getApplicationContext(),getString(R.string.lasterVersion));
//                                                        }
//                                                });
//                                        }
                                }
                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG,"onFailure===");
                        }
                });
        }

        /**
         * 初始化连接
         */
        private void initConnect() {
                //没有连接
                if (MainApplication.isConnect == false) {
                        //界面显示 正在连接.
                        mConnectingDialog = new CenterDialog2(MyRobotActivity.this, CONNECTING);
                        mConnectingDialog.show();
                        setDialogWindowAttr(mConnectingDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
                        handler.sendEmptyMessageDelayed(CONNECTION_FAILURE_FIRST, CONNECTION_TIME);

                }
        }

        //设置对话框显示
        public static void setDialogWindowAttr(Dialog dlg, Context ctx, int width, int height) {
                Window window = dlg.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.gravity = Gravity.CENTER;
                lp.width = width;//宽高可设置具体大小
                lp.height = height;
                dlg.getWindow().setAttributes(lp);
        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.icon_control:
                                if (MainApplication.isConnect == false) {
                                        showConfirmConnectionDialog();
                                }
                                else {
                                startActivity(MyRobotActivity.this, EditorActivity.class);
                                }
                                break;
                        case R.id.icon_editor:
                                if (MainApplication.isConnect == false) {
                                        showConfirmConnectionDialog();
                                }
                                else {
                                startActivity(MyRobotActivity.this, ControlCenterActivity.class);
                                        MsgSendUtils.sendStringMsgToPad(MsgType.RECEIVER_MSG_SWITCH_ACTIVITY, "33&&connsetting");
                                }
                                break;
                        default:
                                break;
                }

        }

        private void showConfirmConnectionDialog() {
                MainApplication.clickDisconnectButton = false;
                idfirst = true;
                mConfirmConnectionDialog = new CenterCommonHintDialog(MyRobotActivity.this, 8);
                mConfirmConnectionDialog.show();
                setDialogWindowAttr(mConfirmConnectionDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x590), (int) getResources().getDimension(R.dimen.x377));
                mConfirmConnectionDialog.setListner(new CenterCommonHintDialog.CenterCommonHintOnlickListner() {
                        @Override
                        public void onClick(int id) {
                                switch (id) {
                                        //当前设备已断开与机器人的连接，若重新连接机器人请进行重连
                                        //取消
                                        case R.id.dialog_hint2_cancel:
                                                mConfirmConnectionDialog.cancel();
                                                break;
                                        //确定
                                        case R.id.dialog_hint2_reconnection:

                                                String currentSSID = getCurrentSSID();
                                                if (WifiUtils.isU05Wifi(currentSSID)) {
                                                        if (!MainApplication.isConnect) {
                                                                MainApplication.getInstance().getServerIp();
                                                        }

                                                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_PAD_CONN_HOTSPOT, currentSSID);

                                                        mConfirmConnectionDialog.cancel();
                                                        centerDialog = new CenterDialog2(MyRobotActivity.this, CONNECTING_FIRST);
                                                        centerDialog.show();
                                                        setDialogWindowAttr(centerDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
                                                        handler.sendEmptyMessageDelayed(CONNECTION_FAILURE_FIRST, CONNECTION_TIME);

                                                }
                                                else {
                                                        ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.not_connected_chest_hotspot));
                                                }
                                                break;
                                }


                        }
                });
        }

        /**
         * 三方联网成功的广播通知.
         */
        BroadcastReceiver mSendResultReceiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
//                        handler.removeCallbacksAndMessages(null);

                        //取消显示所有的对话框.
                        if (mConnectingDialog != null) {
                                mConnectingDialog.cancel();
                                mConnectingDialog = null;
                        }

                        if (centerDialog != null) {
                                centerDialog.cancel();
                        }

                        if (mConfirmConnectionDialog != null) {
                                mConfirmConnectionDialog.cancel();
                        }


                        if (mFailureDialog != null) {
                                mFailureDialog.cancel();
                        }

                        if (mSuccessDialog != null && mSuccessDialog.isShowing()) {
                                return;
                        }


                        //
                        mSuccessDialog = new CenterDialog2(MyRobotActivity.this, CONNECTING_SUCCESS);
                        mSuccessDialog.show();
                        setDialogWindowAttr(mSuccessDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
                        //一秒之后消失对话框
                        handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                        mSuccessDialog.cancel();
                                        mSuccessDialog = null;
                                        //成功连接网络后，切换当前(使用机器人和设置机器人的按钮显示和隐藏)
                                        switchConnBtn();

                                }
                        }, 1000);

                        checkVersion();
                }
        };

        /**
         * 跳转到其他activity
         */
        protected void startActivity(Context context, Class<?> cls) {
                Intent intent = new Intent(context, cls);
                startActivity(intent);
        }


        Handler handler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                        switch (msg.what) {

                                case CONNECTION_FAILURE_FIRST:
                                        //连接失败时，点击重连的调用
                                        if (!MainApplication.isConnect) {
                                                if(mConnectingDialog!=null){
                                                        mConnectingDialog.cancel();
                                                        mConnectingDialog = null;
                                                }
                                                //红色错误提示，只有一个重连button 。
                                                mFailureDialog = new CenterErrorDialog(MyRobotActivity.this);
                                                mFailureDialog.show();
                                                mFailureDialog.setClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View view) {

                                                                String currentSSID = getCurrentSSID();
                                                                if (WifiUtils.isU05Wifi(currentSSID)) {
                                                                        if (!MainApplication.isConnect) {
                                                                                MainApplication.getInstance().getServerIp();
                                                                        }
                                                                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_PAD_CONN_HOTSPOT, currentSSID);
                                                                        mFailureDialog.cancel();
                                                                        centerDialog = new CenterDialog2(MyRobotActivity.this, CONNECTING_FIRST);
                                                                        centerDialog.show();
                                                                        setDialogWindowAttr(centerDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
                                                                        handler.sendEmptyMessageDelayed(CONNECTION_FAILURE_SECOND, CONNECTION_TIME);
                                                                }
                                                                else {
                                                                        ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.not_connected_chest_hotspot));
                                                                }
                                                        }
                                                });
                                        }
                                        break;
                                case CONNECTION_FAILURE_SECOND:
                                        //2种重连的弹框显示
                                        if (!MainApplication.isConnect) {

                                                centerDialog.cancel();
                                                if (idfirst == false) {
                                                        mConfirmConnectionDialog = new CenterCommonHintDialog(MyRobotActivity.this, FIRST_HINT);
                                                }
                                                else {
                                                        mConfirmConnectionDialog = new CenterCommonHintDialog(MyRobotActivity.this, SECOND_HINT);
                                                }

                                                mConfirmConnectionDialog.show();
                                                mConfirmConnectionDialog.setListner(new CenterCommonHintDialog.CenterCommonHintOnlickListner() {
                                                        @Override
                                                        public void onClick(int id) {
                                                                switch (id) {
                                                                        //取消
                                                                        case R.id.counsel_dialog_cancel:
                                                                                mConfirmConnectionDialog.cancel();
                                                                                break;
                                                                        //重连
                                                                        case R.id.counsel_dialog_reconnection:
                                                                                String currentSSID = getCurrentSSID();
                                                                                if (WifiUtils.isU05Wifi(currentSSID)) {
                                                                                        if (!MainApplication.isConnect) {
                                                                                                MainApplication.getInstance().getServerIp();
                                                                                        }
                                                                                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_PAD_CONN_HOTSPOT, currentSSID);
                                                                                        mConfirmConnectionDialog.cancel();
                                                                                        centerDialog = new CenterDialog2(MyRobotActivity.this, CONNECTING_FIRST);
                                                                                        centerDialog.show();
                                                                                        setDialogWindowAttr(centerDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
                                                                                        handler.sendEmptyMessageDelayed(CONNECTION_FAILURE_SECOND, CONNECTION_TIME);
                                                                                }
                                                                                else {
                                                                                        ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.not_connected_chest_hotspot));
                                                                                }

                                                                                break;
                                                                }


                                                        }
                                                });

                                        }
                                        break;

                                case DISCONN_HINT:

                                        btDisconnect.setVisibility(View.GONE);
                                        btConn.setVisibility(View.VISIBLE);

                                        SocketManager.getInstance().destroy();
                                        MainApplication.isConnect = false;
                                        MainApplication.clickDisconnectButton = true;
                                        IpMsgConst.SOCKET_HOST2 = null;
                                        IpMsgConst.SOCKET_HOST = null;
                                        PadSocketManager.getInstance().destroy();
                                        centerDialog.cancel();
                                        break;
                                case DISCONNECT:

                                        if (!disconnectNetSuccess){
                                                if (System.currentTimeMillis() - disconnectTime >30*1000){
                                                        Logger.e(TAG,getString(R.string.disconnected_failed));
                                                        ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.disconnected_failed));
                                                        centerDialog.cancel();
                                                        return;
                                                }
                                                ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.disconnected_again));
                                                Logger.e(TAG,getString(R.string.disconnected_again));
                                                MsgSendUtils.sendStringMsgToPad(MsgType.SEND_3288_DISCONNECT_NETWORK, "disconnect hotspot");
                                            sendEmptyMessageDelayed(DISCONNECT,5000);
                                        }
                                        break;
                        }

                }
        };


        /**
         * 断开网络，同时给胸口和头部发送消息
         * 断开机器人button
         *
         * @param view
         */
        public void disconnectNet(View view) {

                if (!WifiUtils.isU05Wifi(getCurrentSSID())) {
                        ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.not_connected_chest_hotspot));
                        return ;
                }

                handler.removeCallbacksAndMessages(null);
                centerDialog = new CenterDialog2(MyRobotActivity.this, DISCONN_HINT);
                centerDialog.show();
                setDialogWindowAttr(centerDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));
//                handler.sendEmptyMessageDelayed(DISCONN_HINT, 5 * 1000);
                MsgSendUtils.sendStringMsgToPad(MsgType.SEND_3288_DISCONNECT_NETWORK, "disconnect hotspot");
                handler.sendEmptyMessageDelayed(DISCONNECT,5000);
                disconnectTime = System.currentTimeMillis();


//                handler.sendEmptyMessageDelayed(DISCONN_HINT, 20 * 1000);
        }

        /**
         * 三方组网
         * 连接机器人button
         *
         * @param view
         */
        public void connNet(View view) {
                MainApplication.clickDisconnectButton = false;
                disconnectNetSuccess = false;
                centerDialog = new CenterDialog2(MyRobotActivity.this, CONN_HINT);
                centerDialog.show();
                setDialogWindowAttr(centerDialog, MyRobotActivity.this, (int) getResources().getDimension(R.dimen.x500), (int) getResources().getDimension(R.dimen.x200));

                String currentSSID = getCurrentSSID();
                if (WifiUtils.isU05Wifi(currentSSID)) {
                        if (!MainApplication.isConnect) {
                                MainApplication.getInstance().getServerIp();
                        }
                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_PAD_CONN_HOTSPOT, currentSSID);
                        //显示的是设置机器人，说明目前还没有三方组网.
                        btDisconnect.setVisibility(View.VISIBLE);
                        btConn.setVisibility(View.GONE);
                }
                else {
                        ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.not_connected_chest_hotspot));
                }

        }


        private String getCurrentSSID() {
                //获取当前连接的wifi信息
                WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo != null) {
                        return wifiInfo.getSSID();
                }
                return null;


        }


        @Override
        protected void onResume() {
                super.onResume();
//                Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
                switchConnBtn();

                LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,new IntentFilter(ConstUtils.ACTION_DISCONNECT_SUCCESS));



        }


        BroadcastReceiver   mReceiver = new  BroadcastReceiver()
        {
                public void onReceive(Context context, Intent intent) {

                        ToastTools.newInstance(MyRobotActivity.this).showText(getString(R.string.receive_successful));
                         disconnectNetSuccess = true;
                         handler.removeMessages(DISCONNECT);
                         handler.removeMessages(DISCONN_HINT);
                        //延迟消失，让用户感觉一下.
                        handler.sendEmptyMessageDelayed(DISCONN_HINT, 2 * 1000);

                }


        }

        ;


        @Override
        protected void onPause() {
                super.onPause();

                LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);

                disconnectNetSuccess = false;
        }

        private void switchConnBtn() {
                if (MainApplication.isConnect) {
                        btDisconnect.setVisibility(View.VISIBLE);
                        btConn.setVisibility(View.GONE);
                }
                else {
                        btDisconnect.setVisibility(View.GONE);
                        btConn.setVisibility(View.VISIBLE);
                }
        }


        @Override
        protected void onDestroy() {
                super.onDestroy();
                this.unregisterReceiver(mSendResultReceiver);
        }
}
